package com.xunji.user.util;


import cn.hutool.extra.spring.SpringUtil;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class RestTemplateUtil {

    private static RestTemplate restTemplate = SpringUtil.getBean(RestTemplate.class);

    public static <T> T doHttp(String url, HttpMethod method, Object obj, ParameterizedTypeReference<T> parameterizedTypeReference) {
        return doHttp(url, MediaType.APPLICATION_JSON, null, method, obj, parameterizedTypeReference);
    }


    public static <T> T doHttp(String url, MediaType contentType, HttpMethod method, Object obj, ParameterizedTypeReference<T> parameterizedTypeReference) {
        return doHttp(url, contentType, null, method, obj, parameterizedTypeReference);
    }

    public static <T> T doHttp(String url, Map<String, String> headerMap, HttpMethod method, Object obj, ParameterizedTypeReference<T> parameterizedTypeReference) {
        return doHttp(url, null, headerMap, method, obj, parameterizedTypeReference);
    }

    public static <T> T doHttp(String url, MediaType contentType, Map<String, String> headerMap, HttpMethod method, Object obj, ParameterizedTypeReference<T> parameterizedTypeReference) {
        HttpHeaders headers = new HttpHeaders();
        contentType = contentType == null ? MediaType.APPLICATION_JSON : contentType;
        headers.setContentType(contentType);
        if (headerMap != null && headerMap.size() > 0) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                headers.add(entry.getKey(), entry.getValue());
            }
        }
        HttpEntity entity = new HttpEntity(obj, headers);

        ResponseEntity<T> exchange = restTemplate.exchange(url, method, entity, parameterizedTypeReference);
        return exchange.getBody();
    }

}
